<!-- eslint-disable vue/this-in-template -->
<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item
        v-hasPermi="['system:deptCost:isUser']"
        label="是否为个人成本"
        prop="isUser"
      >
        <el-select
          v-model="queryParams.isUser"
          placeholder="请选择是否为个人成本"
          style="width: 240px"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.is_cost_user"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 按人员筛选 -->
      <el-form-item v-if="queryParams.isUser === '1'" v-hasPermi="['system:deptCost:user']" label="人员">
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择人员"
          clearable
          filterable
          style="width: 180px"
        >
          <el-option
            v-for="item in userData"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <!-- 按部门筛选 -->
      <el-form-item v-if="queryParams.isUser === '0'" v-hasPermi="['system:deptCost:type']" label="部门">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择部门"
          clearable
          filterable
          style="width: 180px"
        >
          <el-option
            v-for="dept in deptData"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="dept.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成本类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择成本类型"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.cost_types"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="记录时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="onDateRangeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:deptCost:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="handleSort"
        >排序</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="deptCostList">
      <el-table-column label="成本（万元）" prop="cost" />
      <el-table-column label="成本类型" prop="typeLabel" width="80">
        <template slot-scope="scope">
          {{ scope.row.typeLabel }}
        </template>
      </el-table-column>
      <el-table-column label="是否为个人成本" align="center" prop="isUser">
        <template slot-scope="scope">
          <span>{{ scope.row.isUser == "1" ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="queryParams.isUser === '0'"
        label="部门名称"
        prop="deptName"
      />
      <el-table-column
        v-if="queryParams.isUser === '1'"
        label="用户名称"
        prop="userName"
      />
      <el-table-column label="记录时间" align="center" prop="recordTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:deptCost:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            v-hasPermi="['system:deptCost:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <div>
      <h4>汇总</h4>
    </div>
    <el-table v-loading="loading" :data="summaryList">
      <el-table-column label="汇总名称" prop="summaryName" />
      <el-table-column label="项目成本" prop="projectCost" />
      <el-table-column label="已分配成本" prop="assignedCost" />
      <el-table-column label="总成本" prop="totalCost" />
    </el-table>
    <!-- 编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body :close-on-click-modal="false">
      <el-form
        ref="formData"
        :model="formData"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="分配方式" prop="isUser">
          <el-switch
            v-model="formData.isUser"
            style="display: block; margin-top: 2%"
            active-color="#13ce66"
            inactive-color="#409eff"
            active-text="按部门"
            inactive-text="按人员"
          />
        </el-form-item>
        <el-form-item v-if="formData.isUser" label="部门" prop="deptId">
          <el-select
            v-model="formData.deptId"
            placeholder="请选择部门"
            clearable
            filterable
            style="width: 240px"
          >
            <el-option
              v-for="dept in deptData"
              :key="dept.deptId"
              :label="dept.deptName"
              :value="dept.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!formData.isUser" label="人员" prop="userId">
          <el-select
            v-model="formData.userId"
            placeholder="请选择人员"
            clearable
            filterable
            style="width: 240px"
          >
            <el-option
              v-for="item in userData"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker
            v-model="formData.recordTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="成本(万元)" prop="cost">
          <el-input-number
            v-model="formData.cost"
            controls-position="right"
            :precision="2"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="成本类型" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择成本类型"
            clearable
            filterable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.cost_types"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :disabled="!this.formData.cost"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  costList,
  costDel,
  costAdd,
  costUpDate,
  costSummary
} from '@/api/settlement/costing'
import { userList } from '@/api/settlement/user'
import { deptList } from '@/api/settlement/dept'
// import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'DeptCost',
  dicts: ['is_cost_user', 'cost_types'],
  data() {
    return {
      title: '成本管理',
      deptCostList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dateRange: [],
        isUser: '1',
        type: '',
        deptId: null,
        userId: null
      },
      totalQuery: {
        pageNum: 1,
        pageSize: 999,
        summaryId: null,
        summaryType: 'USER_COST'
      },
      dateRange: [],
      loading: false,
      costList: [],
      formData: {
        id: null,
        recordTime: '',
        cost: '',
        remark: '',
        type: '',
        isUser: false,
        deptId: null,
        userId: null
      },
      total: 0,
      open: false, // 表单校验
      rules: {
        deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
        userId: [{ required: true, message: '请选择人员', trigger: 'change' }],
        recordTime: [
          { required: true, message: '请选择记录时间', trigger: 'change' }
        ],
        cost: [{ required: true, message: '成本不能为空', trigger: 'blur' }],
        type: [
          { required: true, message: '请选择成本类型', trigger: 'change' }
        ]
      },
      userData: [],
      deptData: [],
      summaryList: [],
      sortVisible: 0
    }
  },
  created() {
    this.getList()
    this.getUserList()
    this.getDeptList()
  },
  methods: {
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm('formData')
      this.formData = {}
      this.dateRange = []
    },
    handleSort() {
      this.sortVisible = this.sortVisible === 0 ? 1 : 0
      this.getList()
    },
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除id为"' + row.id + '"的数据项？')
        .then(function() {
          return costDel(row.id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 编辑按钮 */
    handleUpdate(row) {
      this.open = true
      this.title = '编辑'
      this.formData = {
        id: row.id,
        recordTime: new Date(row.recordTime),
        cost: row.cost,
        remark: row.remark,
        type: row.type.toString(),
        isUser: row.isUser === '0',
        deptId: row.deptId,
        userId: row.userId
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          const params = {
            id: this.formData.id ?? null,
            deptId: this.formData.deptId ?? 0,
            cost: this.formData.cost,
            recordTime: new Date(this.formData.recordTime).getTime(),
            remark: this.formData.remark,
            type: Number(this.formData.type),
            isUser: this.formData.isUser ? 0 : 1,
            userId: this.formData.userId ?? 0
          }
          if (this.title === '编辑') {
            params.id = this.formData.id
            costUpDate(params).then((response) => {
              this.$modal.msgSuccess('编辑成功')
              this.open = false
              this.getList()
            })
          } else {
            costAdd(params).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    getList() {
      this.loading = true
      const params = {
        beginTime: this.queryParams.dateRange[0] ?? null,
        endTime: this.queryParams.dateRange[1] ?? null,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        isUser: this.queryParams.isUser,
        type: this.queryParams.type,
        isAsc: this.sortVisible,
        // 新增：根据筛选方式传递 deptId 或 userId
        deptId:
          this.queryParams.isUser === '0' ? this.queryParams.deptId : null,
        userId:
          this.queryParams.isUser === '1' ? this.queryParams.userId : null
      }
      const costParams = {
        summaryId: params.userId || params.deptId,
        summaryType: params.isUser === '1' ? 'USER_COST' : 'DEPT_COST',
        beginTime: params.beginTime,
        endTime: params.endTime
      }
      costSummary(costParams).then((res) => {
        this.summaryList = res.data
      })
      costList(params).then((res) => {
        this.deptCostList = res.data.list.map((item) => {
          item.typeLabel =
            this.dict.type.cost_types.find((a) => Number(a.value) === item.type)
              ?.label || ''
          // 假设后端返回了 allocatedCost 字段，否则你可以在此处计算
          return item
        })
        this.total = res.data.total || 0
      })
      this.loading = false
    },
    onDateRangeChange() {
      if (this.dateRange && this.dateRange.length > 0) {
        // 获取开始日期并设置为当天的第一秒
        const startDate = new Date(this.dateRange[0]) // 获取开始日期
        startDate.setHours(0, 0, 0, 0) // 设置为当天的第一秒
        this.queryParams.dateRange[0] = startDate.getTime() // 转换为时间戳并添加
        if (this.dateRange.length > 1) {
          const endDate = new Date(this.dateRange[1])
          endDate.setHours(23, 59, 59, 999)
          this.queryParams.dateRange[1] = endDate.getTime()
        }
      } else {
        this.queryParams.dateRange = []
      }
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.reset()
      // 重置筛选相关字段
      this.queryParams.isUser = '1'
      this.queryParams.deptId = null
      this.queryParams.userId = null
      this.handleQuery()
      this.getList()
    },
    resetQueryTotal() {
      this.resetForm('queryForm')
      this.reset()
      // 重置汇总相关字段
      this.totalQuery.summaryType = 'DEPT_COST'
      this.totalQuery.summaryId = null
    },
    handleQuery() {
      this.getList()
    },
    getUserList() {
      userList().then((res) => {
        this.userData = res.data
      })
    },
    getDeptList() {
      deptList().then((res) => {
        this.deptData = res.data
      })
    }
  }
}
</script>
